package com.jic.market.impl;

import com.alibaba.fastjson.JSON;
import com.jic.market.entity.*;
import com.jic.market.entity.base.BaseActivity;
import com.jic.market.mapper.*;
import com.jic.market.mapper.base.BaseActivityMapper;
import com.jic.market.mapper.skill.ActivityMerchantConfigMapper;
import com.jic.market.mapper.skill.ActivityStoreConfigMapper;
import com.jic.market.service.PromotionEndJobService;
import com.jic.member.api.rest.MememberActionApi;
import com.jic.member.request.MememberIntegralActionRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author yinhaijun
 * @date: 2020/7/1
 */
@Slf4j
@Service
public class PromotionEndJobServiceImpl implements PromotionEndJobService {

    // 同步的时间段
    private static final long SYNC_TIME_PERIOD = 24 * 3600 * 1000;

    @Autowired
    private PromotionEndProcessMapper promotionEndProcessMapper;

    @Autowired
    private PromotionEntityMapper promotionEntityMapper;

    @Autowired
    private BaseActivityMapper baseActivityMapper;

    @Autowired
    private PatchGrouponThemeEntityMapper patchGrouponThemeEntityMapper;

    @Autowired
    private PromotionMerchantEntityMapper promotionMerchantEntityMapper;

    @Autowired
    private PatchGrouponMerchantEntityMapper patchGrouponMerchantEntityMapper;

    @Autowired
    private ActivityMerchantConfigMapper activityMerchantConfigMapper;

    @Autowired
    private ActivityStoreConfigMapper activityStoreConfigMapper;

    @Resource
    private MememberActionApi mememberActionService;

    @Override
    public void syncSore() {
        // 当前时间
        Date startTime = null;
        Date endTime = null;
        try {
            Date now = new Date();
            DateFormat formatDay = new SimpleDateFormat("yyyy-MM-dd");
            startTime = formatDay.parse(formatDay.format(now.getTime() - SYNC_TIME_PERIOD));
            endTime = formatDay.parse(formatDay.format(now.getTime()));
        } catch (ParseException e) {
            log.error("添加失败", e);
            e.printStackTrace();
        }
        // 根据当前时间生成唯一流水号
        String serialNo = genSerialNo(startTime, endTime);
        log.info("开始执行活动结束同步会员积分开始" + serialNo);
        // 幂等校验
        PromotionEndProcess promotionEndProcess = new PromotionEndProcess();
        promotionEndProcess.setSerialNo(serialNo);
        promotionEndProcess.setStatus(2);
        promotionEndProcess.setCreateTime(new Date());
        promotionEndProcess.setUpdateTime(new Date());
        promotionEndProcess.setDeleteFlag(false);
        promotionEndProcessMapper.insert(promotionEndProcess);
        try{
            syncUserScore(startTime, endTime);
        }catch (Exception e){
            log.info("开始执行活动结束同步会员积分失败" + serialNo, e);
            promotionEndProcess.setStatus(4);
            promotionEndProcess.setUpdateTime(new Date());
            promotionEndProcessMapper.update(promotionEndProcess);
            return;
        }
        promotionEndProcess.setStatus(3);
        promotionEndProcess.setUpdateTime(new Date());
        promotionEndProcessMapper.update(promotionEndProcess);
        log.info("开始执行活动结束同步会员积分成功" + serialNo);
    }

    private String genSerialNo(Date startTime, Date endTime){
        // 格式化
        DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String startTimeStr = format.format(startTime);
        String endTimeStr = format.format(endTime);
        return startTimeStr + endTimeStr;
    }

    private void syncUserScore(Date startTime, Date endTime){
        // 处理通用活动
        List<Long> commonStoreIds = processUserScoreCommon(startTime, endTime);
        // 处理拼团活动
        List<Long> groupStoreIds = processUserScoreGroup(startTime, endTime);
        // 处理优惠券红包活动
        List<Long> discountStoreIds = processUserScoreDiscount(startTime, endTime);
        commonStoreIds.addAll(groupStoreIds);
        commonStoreIds.addAll(discountStoreIds);
        syncRemoteUserScore(commonStoreIds);
    }

    /** 通用活动 */
    private List<Long> processUserScoreCommon(Date startTime, Date endTime) {
        List<Long> storeIds = new ArrayList();
        List<PromotionEntity> promotionEntityList = promotionEntityMapper.queryEnd(startTime, endTime);
        if(null != promotionEntityList && !promotionEntityList.isEmpty()){
            promotionEntityList.forEach(promotionEntity -> {
                // 查询店铺
                PromotionMerchantEntity promotionMerchantEntityQ = new PromotionMerchantEntity();
                promotionMerchantEntityQ.setDeleteFlag(0);
                promotionMerchantEntityQ.setMerchantType(2);
                promotionMerchantEntityQ.setPromotionId(promotionEntity.getId());
                List<PromotionMerchantEntity> promotionMerchantEntityList = promotionMerchantEntityMapper.findAll(promotionMerchantEntityQ);
                // 同步积分
                if(null != promotionMerchantEntityList && !promotionMerchantEntityList.isEmpty()){
                    promotionMerchantEntityList.forEach(promotionMerchantEntity -> storeIds.add(promotionMerchantEntity.getStoreId()));
                }
            });
        }
        return storeIds;
    }

    /** 拼团活动 */
    private List<Long> processUserScoreGroup(Date startTime, Date endTime) {
        List<Long> storeIds = new ArrayList();
        List<PatchGrouponThemeEntity> patchGrouponThemeEntityList = patchGrouponThemeEntityMapper.queryEnd(startTime, endTime);
        if(null != patchGrouponThemeEntityList && !patchGrouponThemeEntityList.isEmpty()){
            patchGrouponThemeEntityList.forEach(promotionEntity -> {
                // 查询店铺
                PatchGrouponMerchantEntity patchGrouponMerchantEntityQ = new PatchGrouponMerchantEntity();
                patchGrouponMerchantEntityQ.setDeleteFlag(0);
                patchGrouponMerchantEntityQ.setMerchantType(2);
                patchGrouponMerchantEntityQ.setPromotionId(promotionEntity.getId());
                List<PatchGrouponMerchantEntity> patchGrouponMerchantEntityList = patchGrouponMerchantEntityMapper.findAll(patchGrouponMerchantEntityQ);
                if(null != patchGrouponMerchantEntityList && !patchGrouponMerchantEntityList.isEmpty()){
                    patchGrouponMerchantEntityList.forEach(promotionMerchantEntity -> storeIds.add(promotionMerchantEntity.getStoreId()));
                }
            });
        }
        return storeIds;
    }

    /** 优惠券红包活动 */
    private List<Long> processUserScoreDiscount(Date startTime, Date endTime) {
        List<Long> storeIds = new ArrayList();
        List<BaseActivity> baseActivityList = baseActivityMapper.queryEnd(startTime, endTime);
        if(null != baseActivityList && !baseActivityList.isEmpty()){
            baseActivityList.forEach(promotionEntity -> {
                // 查询店铺
                PromotionMerchantEntity promotionMerchantEntityQ = new PromotionMerchantEntity();
                promotionMerchantEntityQ.setDeleteFlag(0);
                promotionMerchantEntityQ.setMerchantType(2);
                promotionMerchantEntityQ.setPromotionId(promotionEntity.getId());
                List<PromotionMerchantEntity> promotionMerchantEntityList = promotionMerchantEntityMapper.findAll(promotionMerchantEntityQ);
                // 同步积分
                if(null != promotionMerchantEntityList && !promotionMerchantEntityList.isEmpty()){
                    promotionMerchantEntityList.forEach(promotionMerchantEntity -> storeIds.add(promotionMerchantEntity.getStoreId()));
                }
            });
        }
        return storeIds;
    }

    /** 远程调用会员接口同步积分 */
    private void syncRemoteUserScore(List<Long> storeIdList) {
        Long[] storeIds = storeIdList.toArray(new Long[storeIdList.size()]);
        if(null == storeIds || storeIds.length == 0){
            return;
        }
        MememberIntegralActionRequest request = new MememberIntegralActionRequest();
        request.setObtainMode("9");
        request.setStoreIds(storeIds);
        log.info("远程调用新增积分,request={}", JSON.toJSONString(request));
        mememberActionService.updateStoreMemberIntegralInfo(request);
        log.info("远程调用新增积分结果,response={}", JSON.toJSONString(request));
    }


}
